package com.newlink.building.main.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.util.Log
import android.view.View
import androidx.core.app.ActivityCompat
import com.newlink.building.library_rino.ConnectionController
import com.newlink.building.common_base.base.NL_BaseActivity
import com.newlink.building.common_base.event.CallCreateActionBean
import com.newlink.building.common_base.event.CallCreateBean
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_PROPERTY_MANAGER
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_PROPERTY_MANAGER
import com.newlink.building.common_base.event.TokenVo
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.PropertyManagerData
import com.newlink.building.common_base.utils.PermissionHelper
import com.newlink.building.common_base.widget.CustomMessageDialog
import com.newlink.building.main.R
import com.newlink.building.main.databinding.ActivityPropertyManagerDetailBinding
import com.newlink.building.NL_App.Companion.coreContext
import com.newlink.building.manager.Module_Phone_VoipController
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.linphone.core.Call
import org.linphone.core.Core
import org.linphone.core.CoreListenerStub

/**
 * Created by xiaodong on 2025/4/7.
 */
class Module_Main_PropertyManagerDetailActivityNL : NL_BaseActivity() {

    private lateinit var mBinding: ActivityPropertyManagerDetailBinding
    private var mPropertyManagerData: PropertyManagerData? = null
    var localChannelName: String = ""
    var tokenVo: TokenVo? = null
    override fun attachLayoutRes(): View? {
        mBinding = ActivityPropertyManagerDetailBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {

        try {
            mPropertyManagerData =
                intent.getSerializableExtra("mManagerData") as PropertyManagerData
        } catch (e: Exception) {
            Log.e("PropertyManagerDetailActivity", "--------- $e")
        }

    }

    override fun initView() {
        Log.e("PropertyManagerDetailActivity", "--------- initView $mPropertyManagerData")
        mBinding.titleBar.tvTitleBarCenter.text = getString(R.string.property_manager)
        mBinding.tvName.text = mPropertyManagerData?.name
        mBinding.tvPhone.text = mPropertyManagerData?.aid.toString()
        mBinding.ivCall.setOnClickListener {
            if (!PermissionHelper.required(this).hasPermission(Manifest.permission.RECORD_AUDIO)
            ) {
                checkAudioPermission()
            } else {
//                    makeCall()
                sendCreateChannelEvent()
            }
        }
        coreContext.core.addListener(coreListener)
        initCallErrorMessage()
    }

    private fun initCallErrorMessage() {
        coreContext.callErrorMessageResourceId.observe(
            this
        ) {
            it.consume { message ->
                showSnackBar(message)
            }
        }
    }

    private fun checkAudioPermission() {
        val message = getString(
            R.string.common_permission_audio_message,
            getString(R.string.common_permission_to_setting),
            getString(R.string.common_permission_microphone)
        )
        CustomMessageDialog(this).setTitle(getString(R.string.common_permission_title))
            .setMessage(message)

            .setNegativeButton(
                getString(R.string.cancel_dialog_custom)
            ) { dialog ->
                dialog.dismiss()
                showToast(getString(R.string.common_permission_cancel_alert))
            }
            .setPositiveButton(
                getString(R.string.common_permission_to_setting)
            ) { dialog ->
                requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 0)
                dialog.dismiss()
            }.show()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0) {
            for (i in permissions.indices) {
                when (permissions[i]) {
                    Manifest.permission.RECORD_AUDIO -> if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        //给了权限
                        sendCreateChannelEvent()
                    } else {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(
                                this,
                                Manifest.permission.RECORD_AUDIO
                            )
                        ) {
                            //拒绝
                            checkAudioPermission()
                        } else {
                            openAppSettings()
                        }
                    }
                }
            }
        }
    }

    private fun openAppSettings() {
        val intent = Intent()
        intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        val uri = Uri.fromParts("package", this.packageName, null)
        intent.data = uri
        startActivity(intent)
    }

    fun sendCreateChannelEvent() {
        if (Module_Phone_VoipController.get().isCallingState()) {
            showToast(getString(R.string.outgoing_call_not_invite_again))
            return
        }
        val sipMsgEvent = MessageEvent(
            TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_PROPERTY_MANAGER,
            CallCreateActionBean(aid = agoraId)
        )
        EventBus.getDefault().post(sipMsgEvent)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMsgReceived(event: MessageEvent) {
        when (event.msgType) {
            TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_PROPERTY_MANAGER -> {
                val callCreateBean = event.msgContent as CallCreateBean?
                localChannelName = callCreateBean?.data?.rtcToken?.channelName.orEmpty()
                tokenVo = callCreateBean?.data
                makeCall()
            }
        }
    }

    private val coreListener = object : CoreListenerStub() {
        override fun onCallStateChanged(
            core: Core,
            call: Call,
            state: Call.State,
            message: String,
        ) {
            when (state) {
                /**
                 * 由于在coreContext里OutgoingInit时会确保清除ChannelName,家庭成员呼叫是自己创建的ChannelName需要重新设置一下
                 */
                Call.State.OutgoingProgress -> {
                    if (localChannelName.isNotEmpty()) {
                        ConnectionController.getInstance(this@Module_Main_PropertyManagerDetailActivityNL)
                            .setRemoteChannelName(localChannelName)
                    }
                    if (tokenVo != null) {
                        ConnectionController.getInstance(this@Module_Main_PropertyManagerDetailActivityNL)
                            .convert2AgoraUserToken(tokenVo, agoraId, agoraAppId)
                    }
                }

                else -> {}
            }
        }
    }

    private fun makeCall() {
        Log.e(
            "PropertyManagerDetailActivity",
            "--------- makeCall $mPropertyManagerData ${mPropertyManagerData?.aid.toString()} - ${mPropertyManagerData?.name}"
        )
        Module_Phone_VoipController.get()
            .makeAudioCall(mPropertyManagerData?.aid.toString(), mPropertyManagerData?.name)
    }

    override fun onDestroy() {
        super.onDestroy()
        coreContext.core.removeListener(coreListener)
    }
}